package com.tpo.jnotes.client.layer.view;

import java.awt.Point;
import java.awt.event.ActionListener;
import java.util.HashMap;

import com.tpo.jnotes.client.layer.binding.Binding;
import com.tpo.jnotes.client.layer.view.dialogs.NFrame;
import com.tpo.jnotes.client.lib.interfaces.IView;
import com.tpo.jnotes.client.main.Logging;

public class NView implements IView
{
    private static final int NOTE_WIDTH = 201;
    private static final int NOTE_HEIGHT = 161;
    private static final int NOTE_DISTANCE = 5;
    private static final int NOTES_PER_ROW = 3;
    private static final int DEFAULT_X = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width
        - NOTE_WIDTH;
    private static final int DEFAULT_Y = (java.awt.Toolkit.getDefaultToolkit().getScreenSize().height / 3)
        - NOTE_HEIGHT;

    private Point nextPosition = new Point( DEFAULT_X, DEFAULT_Y );
    private int rowIndex = 1;

    private HashMap< Integer, NFrame > notesList;
    private ActionListener actionListener;

    public NView()
    {
        notesList = new HashMap< Integer, NFrame >();
    }

    @Override
    public void add( int id )
    {
        Logging.trace( "Current position = " + nextPosition );
        NFrame noteFrame = new NFrame( id );
        Binding.bind( noteFrame );
        noteFrame.setActionListener( actionListener );
        noteFrame.setLocation( nextPosition );
        noteFrame.setVisible( true );
        notesList.put( id, noteFrame );
        updateNextPosition();
    }

    @Override
    public void delete( int id )
    {
        NFrame note = notesList.get( id );
        notesList.remove( id );
        note.setVisible( false );
        note.dispose();
    }

    @Override
    public void setActionListener( ActionListener listener )
    {
        this.actionListener = listener;
    }

    private void updateNextPosition()
    {
        if( rowIndex == NOTES_PER_ROW )
        {
            rowIndex = 1;
            nextPosition.x = DEFAULT_X;
            nextPosition.y += NOTE_HEIGHT + NOTE_DISTANCE;
        }
        else
        {
            rowIndex += 1;
            nextPosition.x -= NOTE_WIDTH + NOTE_DISTANCE;
        }
        Logging.trace( "Next position = " + nextPosition );
    }

    @Override
    public int count()
    {
        if( notesList != null )
            return notesList.size();
        else
            return -1;

    }

}
